import { ListResult } from '@/data/result';
import { list } from '@/services/data';
import { convertListToValueEnum } from '@/utils';
import useSWR from 'swr';

const fetcher = async (url: any) => {
  const res: ListResult = await list(url);

  const allMenu = res?.list || [];
  const rootEnumList = allMenu
    ? allMenu.filter(
        (item: any) =>
          item.parentId === undefined || item.parentId === null || item.parentId === '',
      )
    : [];

  const allMenuValueEnum = convertListToValueEnum(allMenu, 'id', 'cnName');
  const allRootMenuValueEnum = convertListToValueEnum(rootEnumList, 'id', 'cnName');

  return {
    allMenu,
    allMenuValueEnum,
    allRootMenuValueEnum,
  };
};
export const useMenus = () => {
  const { data, isLoading, mutate } = useSWR('/system/rbacMenu', fetcher, {
    revalidateOnFocus: false, // 默认不重新验证
    revalidateOnMount: true, // 组件挂载时验证
    revalidateIfStale: true, // 数据过期时重新验证
    dedupingInterval: 30000, // 30秒内重复请求返回缓存数据
    refreshInterval: 0, // 不自动刷新
  });

  const { allMenu = [], allMenuValueEnum = {}, allRootMenuValueEnum = {} }: any = data || {};
  return {
    allMenu,
    allMenuValueEnum,
    allRootMenuValueEnum,
    isLoading,
    mutate,
  };
};
